package com.jinglin.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinglin.controller.ABaseController;
import com.jinglin.entity.dto.TokenUserInfoDto;
import com.jinglin.entity.enums.VideoStatusEnum;

import com.jinglin.entity.po.*;
import com.jinglin.entity.query.StatisticsInfoQuery;
import com.jinglin.entity.vo.PaginationResultVO;
import com.jinglin.entity.vo.ResponseVO;
import com.jinglin.entity.vo.VideoCommentResultVO;
import com.jinglin.entity.vo.VideoPostEditInfoVo;
import com.jinglin.service.*;
import com.jinglin.utils.DateUtil;
import com.jinglin.utils.JsonUtils;

import com.jinglin.web.annotation.GlobalInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.apache.coyote.Response;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/ucenter")
public class UcenterController extends ABaseController {
    @Autowired
    private VideoInfoPostService videoInfoPostService;
    @Autowired
    private VideoInfoFilePostService videoInfoFilePostService;
    @Autowired
    private VideoInfoService videoInfoService;
    @Autowired
    private VideoCommentService videoCommentService;
    @Autowired
    private VideoDanmuService videoDanmuService;
    @RequestMapping("/postVideo")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO postVideo(VideoInfoPost videoInfoPost,
                                String uploadFileList
    ) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        List<VideoInfoFilePost> filePostList = JsonUtils.convertJsonArray2List(uploadFileList, VideoInfoFilePost.class);
        videoInfoPost.setUserId(tokenUserInfoDto.getUserId());
        videoInfoPost.setNickName(tokenUserInfoDto.getNickName());
        videoInfoPost.setAvatar(tokenUserInfoDto.getAvatar());
        videoInfoPostService.saveVideoInfo(videoInfoPost, filePostList);
        return getSuccessResponseVO(null);
    }

    @PostMapping("/loadVideoList")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO loadVideoList(Integer status, Integer pageNo, String videoNameFuzzy) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        String userId = tokenUserInfoDto.getUserId();
        Page<VideoInfoPost> pageObj = new Page<>(pageNo != null ? pageNo : 0, 10);

        LambdaQueryWrapper<VideoInfoPost> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(status!=null,VideoInfoPost::getStatus, status);
        wrapper.eq(VideoInfoPost::getUserId,userId);
        Page<VideoInfoPost> pageInfo = videoInfoPostService.page(pageObj, wrapper);
        PaginationResultVO<VideoInfoPost> resultVO = new PaginationResultVO<>();

        /*
        * 往里面塞各种统计信息
        * */
        List<VideoInfoPost> videoInfoPostList = pageInfo.getRecords();
        for (VideoInfoPost videoInfoPost : videoInfoPostList) {
            VideoInfo videoInfo = videoInfoService.getById(videoInfoPost.getVideoId());
            if (videoInfo != null){
                BeanUtils.copyProperties(videoInfo,videoInfoPost);
            }
        }


        resultVO.setList(videoInfoPostList);
        resultVO.setPageNo((int)pageInfo.getCurrent());
        resultVO.setPageSize((int)pageInfo.getSize());
        resultVO.setPageTotal((int)pageInfo.getPages());
        resultVO.setTotalCount((int)pageInfo.getTotal());
        return getSuccessResponseVO(resultVO);
    }
    @PostMapping("/getVideoCountInfo")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO getVideoCountInfo(){
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        String userId = tokenUserInfoDto.getUserId();
        // 审核成功
        LambdaQueryWrapper<VideoInfoPost> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(VideoInfoPost::getUserId,userId);
        wrapper1.eq(VideoInfoPost::getStatus, VideoStatusEnum.STATUS3.getStatus());
        int auditPassCount = videoInfoPostService.count(wrapper1);

        // 审核不通过
        LambdaQueryWrapper<VideoInfoPost> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(VideoInfoPost::getUserId,userId);
        wrapper2.eq(VideoInfoPost::getStatus, VideoStatusEnum.STATUS4.getStatus());
        int auditFailCount = videoInfoPostService.count(wrapper2);
        // 待审核
        LambdaQueryWrapper<VideoInfoPost> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(VideoInfoPost::getUserId,userId);
        wrapper3.eq(VideoInfoPost::getStatus, VideoStatusEnum.STATUS2.getStatus());
        int inProgress = videoInfoPostService.count(wrapper3);
        HashMap<String, Integer> map = new HashMap<>();
        map.put("auditPassCount",auditPassCount);
        map.put("auditFailCount",auditFailCount);
        map.put("inProgress",inProgress);

        return getSuccessResponseVO(map);
    }
    @PostMapping("/getVideoByVideoId")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO getVideoByVideoId(String videoId){
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        LambdaQueryWrapper<VideoInfoPost> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VideoInfoPost::getUserId,tokenUserInfoDto.getUserId());
        wrapper.eq(VideoInfoPost::getVideoId,videoId);
        VideoInfoPost videoInfo = videoInfoPostService.getOne(wrapper);


        LambdaQueryWrapper<VideoInfoFilePost> fileWrapper = new LambdaQueryWrapper<>();
        fileWrapper.eq(VideoInfoFilePost::getUserId,tokenUserInfoDto.getUserId());
        fileWrapper.eq(VideoInfoFilePost::getVideoId,videoId);
        List<VideoInfoFilePost> list = videoInfoFilePostService.list(fileWrapper);
        VideoPostEditInfoVo vo = new VideoPostEditInfoVo(videoInfo,list);
        return getSuccessResponseVO(vo);
    }
    @PostMapping("/saveVideoInteraction")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO saveVideoInteraction(String videoId,String interaction){
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        String userId = tokenUserInfoDto.getUserId();
        LambdaUpdateWrapper<VideoInfoPost> postWrapper = new LambdaUpdateWrapper<>();
        postWrapper.eq(VideoInfoPost::getVideoId,videoId);
        postWrapper.eq(VideoInfoPost::getUserId,userId);
        postWrapper.set(VideoInfoPost::getInteraction,interaction);
        videoInfoPostService.update(postWrapper);

        LambdaUpdateWrapper<VideoInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(VideoInfo::getVideoId,videoId);
        wrapper.eq(VideoInfo::getUserId,userId);
        wrapper.set(VideoInfo::getInteraction,interaction);
        videoInfoService.update(wrapper);

        return getSuccessResponseVO(null);
    }
    @PostMapping("/loadAllVideo")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO loadAllVideo(){
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        String userId = tokenUserInfoDto.getUserId();
        LambdaQueryWrapper<VideoInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VideoInfo::getUserId,userId);
        List<VideoInfo> list = videoInfoService.list(wrapper);
        return getSuccessResponseVO(list);
    }
    @PostMapping("/loadComment")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO loadComment(String videoId,Integer pageNo,Integer pageSize){
        PaginationResultVO paginationResultVO = videoCommentService.loadCommentManage(videoId, pageNo, pageSize, getTokenUserInfoDto().getUserId(),null);
        return getSuccessResponseVO(paginationResultVO);
    }
    @PostMapping("/delComment")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO delComment(String commentId){
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        videoCommentService.delComment(commentId,tokenUserInfoDto.getUserId());
        return getSuccessResponseVO(null);
    }

    @PostMapping("/loadDanmu")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO loadDanmu(String videoId,Integer pageNo,Integer pageSize){
        PaginationResultVO paginationResultVO = videoDanmuService.loadDanmuManage(videoId, pageNo, pageSize, getTokenUserInfoDto().getUserId(),null);
        return getSuccessResponseVO(paginationResultVO);
    }
    @PostMapping("/delDanmu")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO delDanmu(String danmuId){
        LambdaQueryWrapper<VideoDanmu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VideoDanmu::getDanmuId,danmuId);
        videoDanmuService.remove(wrapper);
        return getSuccessResponseVO(null);
    }
    @PostMapping("/deleteVideo")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO deleteVideo(String videoId){
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        String userId = tokenUserInfoDto.getUserId();
        videoInfoService.deleteVideo(videoId,userId);
        return getSuccessResponseVO(null);
    }


    @Resource
    private StatisticsInfoService statisticsInfoService;

    @RequestMapping("/getActualTimeStatisticsInfo")
    @GlobalInterceptor
    public ResponseVO getActualTimeStatisticsInfo() {
        String preDate = DateUtil.getBeforeDayDate(1);
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        StatisticsInfoQuery param = new StatisticsInfoQuery();
        param.setStatisticsDate(preDate);
        param.setUserId(tokenUserInfoDto.getUserId());
        List<StatisticsInfo> preDayData = statisticsInfoService.findListByParam(param);
        Map<Integer, Integer> preDayDataMap = preDayData.stream().collect(Collectors.toMap(StatisticsInfo::getDataType, StatisticsInfo::getStatisticsCount, (item1, item2) -> item2));
        Map<String, Integer> totalCountInfo = statisticsInfoService.getStatisticsInfoActualTime(tokenUserInfoDto.getUserId());
        Map<String, Object> result = new HashMap<>();
        result.put("preDayData", preDayDataMap);
        result.put("totalCountInfo", totalCountInfo);
        return getSuccessResponseVO(result);
    }

    @RequestMapping("/getWeekStatisticsInfo")
    @GlobalInterceptor
    public ResponseVO getWeekStatisticsInfo(Integer dataType) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        List<String> dateList = DateUtil.getBeforeDates(7);

        StatisticsInfoQuery param = new StatisticsInfoQuery();
        param.setDataType(dataType);
        param.setUserId(tokenUserInfoDto.getUserId());
        param.setStatisticsDateStart(dateList.get(0));
        param.setStatisticsDateEnd(dateList.get(dateList.size() - 1));
        param.setOrderBy("statistics_date asc");
        List<StatisticsInfo> statisticsInfoList = statisticsInfoService.findListByParam(param);

        Map<String, StatisticsInfo> dataMap = statisticsInfoList.stream().collect(Collectors.toMap(item -> item.getStatisticsDate(), Function.identity(), (data1, data2) -> data2));
        List<StatisticsInfo> resultDataList = new ArrayList<>();
        for (String date : dateList) {
            StatisticsInfo dataItem = dataMap.get(date);
            if (dataItem == null) {
                dataItem = new StatisticsInfo();
                dataItem.setStatisticsCount(0);
                dataItem.setStatisticsDate(date);
            }
            resultDataList.add(dataItem);
        }
        return getSuccessResponseVO(resultDataList);
    }

}
